import uuid
import sqlite3
import socket
import time 
import base64
import json
import threading
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
import backend.DID.DID_interface as did_interface
import backend.P2P.auth as auth
import backend.P2P.info_sync as info_sync

#全局变量
my_joined_groups = {}  # 我所在的群聊
# 格式：my_joined_groups = {
#     "group_001": [
#         {"id": "user1", "ip": "192.168.1.2", "username": "Alice"},
#         {"id": "user2", "ip": "192.168.1.3", "username": "Bob"},
#     ],
#     "group_002": [
#         {"id": "user3", "ip": "192.168.1.4", "username": "Charlie"},
#     ],
# }
group_members_status = {}#我所在群聊的群成员状态
# 格式：group_members_status = {
#     "groupId_1": {
#         "username1": {
#             "user_id": "abc123",
#             "ip": "192.168.1.10",
#             "last_seen": 1721459999   # 时间戳，记录最后一次广播在线的时间，凭借这里的更新时间间隔判断是否下线
#         },
#         "username2": {
#             "user_id": "def456",
#             "ip": "192.168.1.11",
#             "last_seen": 1721459923
#         },
#         ...
#     },}

# 离线用户记录（key: group_id -> username -> last_seen）
offline_users = {}

# 超过该时间间隔视为掉线（单位：秒）
OFFLINE_TIMEOUT = 10

#创建群聊!!!!!!!!!!
def createGroup(groupname,creator_did, receivers,create_time):

    """
    创建群聊：
    - creator: 当前创建群聊的用户(dict 类型，如 {"id": "1001", "username": "Alice", "ip": "192.168.1.10", "role": "owner", "online": True})
    - receivers: 其他成员列表（每个元素是 dict,结构同上）
    """
    # 创建唯一群 ID
    group_id = str(uuid.uuid4())
    # group_name = f"群聊_{create_time}"
    
    with sqlite3.connect("p2p.db", check_same_thread=False) as conn:
            cursor = conn.cursor()

            #去用户表查询群主信息
            cursor.execute('SELECT id, name, ip FROM user WHERE id = ?', (creator_did,))
            row = cursor.fetchone()

            if not row:
                raise ValueError(f"未找到DID号为 {creator_did} 的用户信息")
            
            # 构造群主信息，补全缺失字段：role 默认 owner
            creator_member = {
                "id": row[0],
                "username": row[1],
                "role": "creator",
                "online":True
                "online":True
            }
            
            for member in receivers:
                cursor.execute('''select online from friends where id = ?''', (member["id"],))
                row = cursor.fetchone()
                online = int(row[0]) if row else 0
                member["online"] = online  # 强制赋值

            #members这个字段为：[{"id":"","username":"","role":"","online":""},{}],"
            members = [creator_member] + receivers#将群主作为members的第一个元素存放

            # 存入数据库时转为 JSON 字符串
            members_json = json.dumps(members, ensure_ascii=False)
         
            # 存入数据库
            try:
                cursor.execute('''
                    INSERT INTO tblGroup (groupId, groupname, members, timestamp, owner)
                    VALUES (?, ?, ?, ?, ?)
                ''', (group_id, groupname, members_json, create_time, creator_did))
            except Exception as e:
                print("[错误] 插入群聊信息失败：", e)

                    # 提取成员id列表
    member_ids = [member["id"] for member in members]
    print(f"成员ID列表: {member_ids}")

    try:
        # 调用DID模块创建群密钥并存入区块链
        did_interface.create_and_share_groupkey(group_id, member_ids)
        group_created = True
    except Exception as e:
        print("群密钥创建失败：", e)
        group_created = False

    # 如果群聊创建成功，通知所有群成员：
    if group_created:
        # 通知所有在线群成员群聊已经创建完毕
        remind_group_members(creator_did, group_id, groupname, members)
    else:
        print(" 群聊创建成功，但群密钥创建失败，未通知成员")
    
    return {
           "groupId":group_id,
           "groupname":groupname
           }
#通知群成员
def remind_group_members(creator_did,group_id, groupname, members):

    """
    使用 Socket 通知每位在线群成员的后端服务：群聊已创建
    """
    message = {
        "action": "createGroup",
        "creator":creator_did,
        "data": {
            "groupId": group_id,
            "groupName": groupname,
            "timestamp": int(time.time()),
            "members": members
        }
    }

    # 广播给局域网所有人
    try:
        udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        udp_socket.sendto(json.dumps(message).encode('utf-8'), ('192.168.72.255', 23456))
        udp_socket.close()
        print(f"创建群聊 {groupname} 广播成功")
    except Exception as e:
        print(f"广播失败：{e}")

    for member in members:
        print(f"成员：{member['username']} online 字段类型和值：{type(member['online'])} {member['online']}")
        if not member.get("online"):
            store_offline_message(member["username"], message)
            print(f"{member['username']} 离线，已保存离线消息")
        
#每个群成员相互记录状态，由于每个人上线就会广播自己的在线状态，且每10秒广播一次，那么假如10秒中之后没有收到群成员的广播信息，
#那么从此刻开始就帮该下线成员记录他离线期间的消息，存入专属于该离线成员的临时离线文件中，等他上线再发给他
#1.假设广播格式：
# {
#     "type": "online_status",
#     "username": "Alice",
#     "user_id": "abc123",
#     "group_id":["123456",""],#该成员的所在的所有群id
#     "ip": "192.168.1.10",
#     "timestamp":"12375681908"
#     "message": "我在线"
# }

#查询我所在的群聊的id
def find_my_group_ids(my_did):
    with sqlite3.connect("p2p.db", check_same_thread=False) as conn:
            cursor = conn.cursor()
    cursor.execute("SELECT groupId FROM tblGroup WHERE owner = ?", (my_did,))
    rows = cursor.fetchall()
    group_ids = [row[0] for row in rows]

    return group_ids

#处理广播收到的消息,群成员之间监听各自所在的群聊的群成员的广播，相互记录在线状态，以实现后续离线消息的重发
def handle_broadcast(data, my_group_ids):
    username = data.get("username")
    user_id = data.get("user_id")
    ip = data.get("ip")
    group_ids = data.get("group_id", [])
    current_time = data.get("timestamp")

    for group_id in group_ids:
        if group_id not in my_group_ids:
            continue  # 不是我参与的群，跳过

        if group_id not in group_members_status:
            group_members_status[group_id] = {}

        # 先检查该群内现有成员是否掉线
        for member, info in list(group_members_status[group_id].items()):#.items()：是遍历这个字典的键值对
            last_seen = info["last_seen"]
            if current_time - last_seen > OFFLINE_TIMEOUT:
                # 掉线
                if group_id not in offline_users:
                    offline_users[group_id] = {}
                if member not in offline_users[group_id]:
                    # print(f"{member} 在群 {group_id} 掉线，启用离线记录")
                    offline_users[group_id][member] = last_seen

        # 如果这个成员是重新上线
        if group_id in offline_users and username in offline_users[group_id]:
            # print(f"{username} 在群 {group_id} 重新上线，转发离线消息")
            resend_offline_messages(username, group_id, ip)
            del offline_users[group_id][username]

        # 更新在线状态
        group_members_status[group_id][username] = {
            "user_id": user_id,
            "ip": ip,
            "last_seen": current_time
        }
        # print(f"更新 {username} 在群 {group_id} 的在线状态：{group_members_status[group_id][username]}")

#判断该成员是否是我所在群聊的用户
def is_my_group_member(sender_id):
    for group_id, members in my_joined_groups.items():
        for member in members:
            if member["id"] == sender_id:
                return True
    return False

#保存为离线消息文件，为每个人保存一份还是一份里面保存多个人的离线消息？
def store_offline_message(user_id, message):
    """
    将消息写入离线文件
    """
    with open(f"offline_{user_id}.json", "a", encoding="utf-8") as f:
        f.write(json.dumps(message) + "\n")

#离线消息重发
def resend_offline_messages(user_id, ip, port=23456):
def resend_offline_messages(user_id, ip, port=23456):
    """
    读取并发送某个用户的离线消息，然后删除对应离线消息文件
    """
    filename = f"offline_{user_id}.json"
    if not os.path.exists(filename):
        # print(f"没有离线消息需要发送给 {user_id}")
        return

    try:
        with open(filename, "r", encoding="utf-8") as f:
            lines = f.readlines()

        udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        for line in lines:
            try:
                message = json.loads(line.strip())
                action = message.get("action")

                if action == "createGroup":
                    # create_group消息直接原样转发
                    udp_socket.sendto(json.dumps(message).encode("utf-8"), (ip, port))
                    print(f"已重发一条 createGroup 离线消息给 {user_id}@{ip}")

                elif action == "groupChat":
                    groupID = message.get("groupId")
                    DID = message.get("sender")
                    # 只加密data部分（即群聊内容），而不是整个消息
                    data = message.get("data")
                    if not isinstance(data, str):
                        data = json.dumps(data, ensure_ascii=False)
                    encrypted_data = did_interface.group_meg_encrypt(groupID, DID, data)
                    if not encrypted_data:
                        print(f"消息加密失败，跳过此条")
                        continue
                    encrypted_message_b64 = base64.b64encode(encrypted_data).decode("utf-8")
                    packageEncrypted_msg = {
                        "action": "groupChat",
                        "sender": DID,
                        "groupId": groupID,
                        "groupname": message.get("groupname", ""),
                        "data": encrypted_message_b64
                    }
                    udp_socket.sendto(json.dumps(packageEncrypted_msg).encode("utf-8"), (ip, port))
                    print(f"已重发一条 groupChat 离线消息给 {user_id}@{ip}")

                else:
                    print(f"未知类型离线消息，action={action}，跳过")
                    continue

            except Exception as e:
                print(f"重发送消息失败: {e}")

        udp_socket.close()
        os.remove(filename)
        print(f"所有离线消息已发送完毕，删除文件 {filename}")

    except Exception as e:
        print(f"处理离线消息失败: {e}")

#创建群聊时，群成员后端监听，处理接收到的群聊创建完毕的信息，在这里启动创建群聊的离线消息重发，并通知前端
def listen_create_group_broadcast(message,socketio):
    
    print("你被拉入了新群聊") 
    with sqlite3.connect("p2p.db", check_same_thread=False) as conn:
            cursor = conn.cursor()
            sender_did = message["creator"]
            group_id = message["data"]["groupId"]
            group_name = message["data"]["groupName"]
            group_members = message["data"]["members"]
            create_time = message["data"]["timestamp"]
                
            cursor.execute("SELECT id FROM current_user")
            row = cursor.fetchone()
            if row:
                    self_id = row[0]
            else:
                    self_id = None 
            members_json = json.dumps(group_members)
            # 写入本地数据库、通知前端等
            cursor.execute('''
                    INSERT OR IGNORE INTO tblGroup (groupId, groupname, members, timestamp,owner)
                        VALUES (?, ?, ?, ?,?)
                    ''', (group_id, group_name, members_json, create_time,self_id))


    print(f"已保存群聊 {group_name} 到本地数据库")
    #通知群成员这条还是要显示到页面上，后端对前端发起请求
    request_display_create_group_message(socketio,message,sender_did,group_id)

#群聊聊天，发送消息
def send_message(action,sender_did,groupname, group_id, message):  
# message前端直接提交给我的,是前端发给后端的请求结构体中的“data"
#   message = data里面的字段可自定义来对应不同的操作
#                 "data":{
#                         "groupname":"group_name",
#                         "username":"name",
#                         "msg_type":"text",
#                         "message":"你好！",
#                         "timestamp":1721391429                 
#                 }
    # print (message)
    # print("群id:",group_id)
    # print("发送者DID:",sender_did)
    try:
        # 1. 加密群聊消息用于广播
        encrypted_message = did_interface.group_meg_encrypt(group_id,sender_did, message)
        print ("机密信息：",encrypted_message)
        if not encrypted_message:
            print("群聊消息加密失败，取消发送")
            return
        #查询发送者的用户名
        with sqlite3.connect("p2p.db", timeout=5, check_same_thread=False) as conn:
            cursor = conn.cursor()
            cursor.execute('''SELECT name FROM user WHERE id = ?''', (sender_did,))
            row = cursor.fetchone()
            if row:
                sender_name = row[0]
            else:
                print(f"未找到发送者DID {sender_did} 的用户名，使用默认名")
                sender_name = "未知用户"
            encrypted_message_b64 = base64.b64encode(encrypted_message).decode("utf-8")
            #广播的消息结构体
            packageEncrypted_msg = {
                "action": action ,
                "sender_name": sender_name,
                "sender": sender_did,
                "groupId": group_id,
                "groupname":groupname,
                "data":encrypted_message_b64,  # 加密后的消息内容
            
            }
            # print("加密后的消息包：", packageEncrypted_msg)
            # 2. 使用UDP广播发送加密消息
            udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            udp_socket.sendto(json.dumps(packageEncrypted_msg).encode('utf-8'), ("192.168.72.255", 23456))
            udp_socket.close()
            print("群聊消息已广播发往端口号23456")
        

            # 3. 获取本机设备信息，用于加密存储
            device_info = auth.get_device_info()
            cpu_id = device_info.get("cpu_id", "")
            disk_id = device_info.get("disk_id", "")
            product_id = device_info.get("product_id", "")
            print("本机设备信息：", cpu_id, disk_id, product_id)

            # 4. 加密原始消息用于存储
            encrypted_storage_message= did_interface.encrypt(cpu_id, disk_id, product_id, message)
            print("加密需要存储的信息：",encrypted_storage_message)
            if not encrypted_storage_message:
                print("本地存储加密失败")
                return

            # 说明是该用户正在登录该设备，那么查询信息的时候也只查询这个用户即可
            cursor.execute('''select id from current_user ''')#current_user表即是当前在线用户
            row = cursor.fetchone()
            if row:
                owner_did = row[0]
            else:
                owner_did = None
            # 5. 将加密后的原始消息存入本地数据库
            save_group_message(group_id, sender_did,sender_name, encrypted_storage_message,owner_did)

        print("原始消息已加密并存储成功")
        return 1
    
    except Exception as e:
        print(f"发送群聊消息失败: {e}")
        return 0
#接收群消息，并解密，呈现到前端，再次加密，存储到数据库
def recv_message(socketio):
    print("开始监听群聊消息...")
    def listen():
        try:
            # 1. 打开UDP监听socket
            udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            udp_socket.bind(("0.0.0.0", 23456))
            print("正在监听群聊消息端口23456...")

            while True:
                data, addr = udp_socket.recvfrom(65535)#data= packageEncrypted_msg,或者是收到每个人的在线广播
                print(f"收到来自 {addr} 的广播消息")
                # print ("收到的消息内容：", data)
                try:
                    # 先解码再反序列化
                    data_str = data.decode('utf-8')
                    data_json = json.loads(data_str)
                    # print("收到的消息内容：", data_json)
                except Exception as e:
                    print(f" 消息解码或反序列化失败: {e}")
                    continue
                with sqlite3.connect("p2p.db", check_same_thread=False) as conn:
                    cursor = conn.cursor()           
                    # 2. 查询当前登录用户（即owner）
                    cursor.execute("SELECT id FROM current_user ")
                    row = cursor.fetchone()
                    if row:
                        my_did = row[0]
                    else:
                        print("未检测到登录用户，跳过消息")
                        continue
                    
                    #寻找我所在的群聊的所有id
                my_group_ids=find_my_group_ids(my_did)

                try:
                    # 解析明文字段
                    action = data_json.get("action")
                    
                    action = data_json.get("action")
                    
                    
                    #如果action == groupChat，执行解密，和加密存储
                    if data_json["action"] == "groupChat":
                        sender_did = data_json.get("sender")

                        if sender_did == my_did:
                            print("收到自己发出的消息，跳过处理")
                            continue
                        sender_name = data_json.get("sender_name")  # 获取发送者名称
                        group_id = data_json.get("groupId")
                        encrypted_payload = data_json.get("data") # 获取加密的字符串
                        # 解码成原始字节
                        encrypted_payload_bytes = base64.b64decode(encrypted_payload)
                        # print(f"收到 来自 {sender_did} 的加密消息：", encrypted_payload_bytes)

                        #如果是我所在的群聊，则执行解密，加密存储消息
                        if group_id in my_group_ids:
                            # print (group_id, "是我所在的群聊")
                        # 解密 data 字段
                            decrypted_payload = did_interface.group_meg_decrypt(group_id,my_did,encrypted_payload_bytes)  # 返回的是字符串或字典
                            # print(f"收到[来自 {sender_did} 解密后的消息：", decrypted_payload)
                            # 如果解密后是字符串，尝试转成字典（json.loads）
                            if isinstance(decrypted_payload, str):
                                try:
                                    decrypted_payload = json.loads(decrypted_payload)
                                except json.JSONDecodeError:
                                    pass  # 保留为字符串
                                # 向前端请求显示消息，把消息传给前端
                    
                            # 打印或处理消息
                            # print(f"收到[群聊][{group_id}] 来自 {sender_did} 的消息：", decrypted_payload)

                             # 3. 获取本机设备信息，用于加密存储
                            device_info = auth.get_device_info()
                            cpu_id = device_info.get("cpu_id", "")
                            disk_id = device_info.get("disk_id", "")
                            product_id = device_info.get("product_id", "")

                            print("准备调用 request_display_group_message")
                            request_display_group_message(socketio,sender_name,decrypted_payload,sender_did,group_id)

                            #调用存储加密函数：
                            encrypted_storage_message=did_interface. encrypt(cpu_id, disk_id, product_id,decrypted_payload)
                            #存储加密后的信息
                            save_group_message(group_id,sender_did,sender_name,encrypted_storage_message,my_did)
                            
               

                    #如果action== “online_status"，则这条消息是网络中的广播每个人的在线消息，则要判断这个群成员是否离线过又上线       
                    if data_json["action"] == "online_status":
                        if sender_did == my_did:
                                print("收到自己发出的消息，跳过处理")
                                continue
                        else:
                               handle_broadcast(data_json, my_group_ids)
                    #    print(f"收到[在线状态] 来自 {data_json['id']} 的消息：", data_json)
                    

                    #如果action == "createGroup",通知群成员,需存这条消息，但无需加密
                    if data_json["action"] == "createGroup":
                        sender_did = data_json.get("creator")
                        if sender_did == my_did:
                            print("收到自己发出的消息，跳过处理")
                            continue
                        else:
                            listen_create_group_broadcast(data_json,socketio)

                    # #群主修改了群名称，群成员收到并修改群名称
                    # if data["action"] =="change_groupname":
                    #     member_change_groupname(data)
                    
                    # #@群成员
                    # if data["action"] =="notice":
                    #    recv_notice_members(data,my_did)

                except Exception as e:
                    print(f"[错误] 解密或处理消息失败: {e}")

        except Exception as e:
            print(f"群聊接收监听失败: {e}")

     # 用线程启动监听
    t = threading.Thread(target=listen)
    t.start()

#存储加密后的群消息
def save_group_message(group_id,sender_did,sender_name,encrypted_storage_message,owner_did):
    with sqlite3.connect("p2p.db",timeout=5, check_same_thread=False) as conn:
            cursor = conn.cursor()
            try:
                receiver = "all"   # 群聊默认广播给所有人
                owner = owner_did # 默认当前登录用户
                
                # 插入前先查询是否有重复记录
                cursor.execute('''
                    SELECT 1 FROM group_message 
                    WHERE groupId = ? AND sender = ? AND sender_name = ? AND receiver = ? AND message = ? AND owner = ?
                ''', (group_id, sender_did, sender_name, receiver, encrypted_storage_message, owner))

                if cursor.fetchone():
                    print("该消息已存在数据库中，跳过存储")
                    return

                cursor.execute('''
                    INSERT INTO group_message (sender, sender_name, receiver, message, groupId, owner)
                    VALUES (?, ?, ?, ?, ?, ?)
                ''', (
                    sender_did,
                    sender_name,
                    receiver,
                    encrypted_storage_message,
                    group_id,
                    owner
                ))
                print("加密后的消息已成功保存到数据库")
            except Exception as e:
                print(f"保存群聊消息到数据库失败: {e}")

#获取群聊聊天记录
def load_groupChat_history(group_id): 
    with sqlite3.connect("p2p.db", check_same_thread=False) as conn:
        cursor = conn.cursor()
        cursor.execute('''SELECT id FROM current_user''')
        row = cursor.fetchone()
        owner_did = row[0]

        cursor.execute('''
            SELECT sender, sender_name, receiver, message, groupId, owner 
            FROM group_message 
            WHERE groupId = ? AND owner = ?
        ''', (group_id, owner_did,))
        res = cursor.fetchall()

        if not res:
            print("没有找到该群聊的聊天记录")
            return []

        # 获取设备信息
        device_info = auth.get_device_info()
        cpu_id = device_info.get("cpu_id", "")
        disk_id = device_info.get("disk_id", "")
        product_id = device_info.get("product_id", "")

        result = []
        for sender, sender_name, receiver, message, groupId, owner in res:
            try:
                decrypted_message = did_interface.decrypt(cpu_id, disk_id, product_id, message)

                # 解密后内容处理
                if isinstance(decrypted_message, bytes):
                    decrypted_message_str = decrypted_message.decode('utf-8', errors='ignore')
                elif isinstance(decrypted_message, (str, dict)):
                    decrypted_message_str = decrypted_message
                else:
                    decrypted_message_str = str(decrypted_message)

                # 如果已经是 dict，就跳过解析
                if isinstance(decrypted_message_str, dict):
                    decrypted_message_json = decrypted_message_str
                elif isinstance(decrypted_message_str, str):
                    try:
                        decrypted_message_json = json.loads(decrypted_message_str)
                    except Exception:
                        decrypted_message_json = {
                            "message": decrypted_message_str,
                            "timestamp": int(time.time())
                        }
                else:
                    decrypted_message_json = {
                        "message": "[未知消息格式]",
                        "timestamp": int(time.time())
                    }

            except Exception as e:
                print(f"解密消息失败: {e}")
                decrypted_message_json = {
                    "message": "[解密失败]",
                    "timestamp": int(time.time())
                }

            # 最终确保是字典，并包含字段
            if not isinstance(decrypted_message_json, dict):
                decrypted_message_json = {
                    "message": str(decrypted_message_json),
                    "timestamp": int(time.time())
                }


            result.append({
                "sender": sender,
                "sender_name": sender_name,
                "message": decrypted_message_json["message"],
                "timestamp": decrypted_message_json["timestamp"]
            })

        return result

#向前端请求，显示消息,接口14
def request_display_group_message(socketio,sender_name,decrypted_payload,sender_did,group_id):
    message ={ 
              "action":"groupChat",
              "sender":sender_did,
              "senderName":sender_name,
              "groupId": group_id,
              "message":decrypted_payload['message'],
             "timestamp": decrypted_payload.get("timestamp", int(time.time())),
             }
    print("向前端请求显示群聊消息：", decrypted_payload)
    socketio.emit('client', message)

#向前端请求，显示群聊创建成功的消息,接口15
def request_display_create_group_message(socketio,message,sender_did,group_id):
    """
    向前端请求显示群聊创建成功的消息
    """
    create_message = {
        "action": "createGroup",
        "sender": sender_did,
        "groupId": group_id,
        "data": message["data"],
    }
    socketio.emit('client', create_message)


    

# #修改群聊名称,群主方
# def master_change_groupname(data):#此处的data就是前端传进来的信息，需要包括group_id,groupname,new_groupname,owner(sender_did),但是注意，只有群主可以改
    
#     """
#     只有群主可以更改群名
#     data = {
#         "groupId": "群ID",
#         "groupname": "旧群名",
#         "new_groupname": "新群名",
#         "sender": "群主DID"
#     }
#     """
#     group_id = data.get("groupId")
#     old_groupname = data.get("groupname")
#     new_groupname = data.get("new_groupname")
#     sender = data.get("sender")

#     # 查询群成员
#     cursor.execute("SELECT members FROM tblGroup WHERE groupId = ?", (group_id,))
#     result = cursor.fetchone()
#     if not result:
#         print("群不存在")
#         return

#     try:
#         members = json.loads(result[0])
#     except:
#         print("群成员字段解析失败")
#         return

#     # 群主验证（群主是 members[0]）
#     if sender != members[0]["id"]:
#         print("非群主无法修改群名称")
#         return

#     # 修改数据库中的群名
#     cursor.execute("UPDATE tblGroup SET groupname = ? WHERE groupId = ?", (new_groupname, group_id))
#     connect.commit()
#     print(f"群聊名称更新为：{new_groupname}")

#     # 构造用于 send_message 的标准消息结构体
#     message_data = {
#         "action":"change_groupname",
#         "message": f"群主将群名称更改为「{new_groupname}」",
#         "msg_type": "system",   # 你可以用 "system" 表示非用户普通消息
#         "timestamp": time.time(),
#         "change_type": "groupname_update",
#         "new_groupname": new_groupname
#     }

#     # 统一使用 send_message 进行群广播
#     send_message(sender, old_groupname, group_id, message_data)

#修改群名称，群成员方  
# def member_change_groupname(message):#收到的广播message
#     group_id = message.get("groupId")
#     new_groupname = message["data"].get("new_groupname")
#     #判断是否是我在的群聊：
#     cursor.execute('''select id from current_user''')
#     row = cursor.fetchone()
#     my_did = row[0]
#     #找到我所有的群聊id
#     my_group_ids = find_my_group_ids(my_did)

#     if group_id in my_group_ids:
#         # 更新数据库
#         cursor.execute("UPDATE tblGroup SET groupname = ? WHERE groupId = ?", (new_groupname, group_id))
#         connect.commit()
#         print(f"已将群聊 {group_id}的名称更新为：{new_groupname}")
        
#         # 通知前端刷新界面（示意，可改为信号机制或接口回调）
#         notify_front_groupname_changed(group_id, new_groupname)
#     else:
#         print("不是我所在的群聊需要修改群名称，跳过")

#发送@群成员的那条消息
# def send_message_with_remind(sender_did, groupname, group_id, message):#owner是当前用户的did
# 前端封装消息的结构：
# {
#   "action": "notice",
#   "sender": "sender_did",
#   "groupId": "group-1234",
#   "groupname":"group"
#   "data":{
#   "message": "@Alice 明天开会不要迟到",
#   "mentions": ["Alice_1234",""],  # 被@的用户id列表
#   "timestamp": 1721459325
#        }
# }
    # mentions = []
    # mentions = message.get("mentions")#被@的群成员id列表
    # if mentions:
    #     # 调用send_message 函数，加密发送这条@消息
    #     send_message(sender_did, groupname, group_id, message)
    #     print("已发送@提醒给对应的成员")

#被@的群成员，收到@消息，特殊提醒时的反应   
# def recv_notice_members(message,my_did):
#     sender_id = message.get("sender")
#     group_id = message.get("groupId")
#     groupname = message.get("groupname")
#     encrypted_payload = message.get("data")
#     # 解密 data 字段
#     decrypted_payload = did_interface.group_meg_decrypt(group_id,my_did,encrypted_payload)  # 返回的是字符串或字典

#     # 如果解密后是字符串，尝试转成字典（json.loads）
#     if isinstance(decrypted_payload, str):
#         try:
#             decrypted_payload = json.loads(decrypted_payload)
#         except json.JSONDecodeError:
#             pass  # 保留为字符串

#         # 打印或处理消息
#         print(f"收到我被群聊{group_id}中的成员{sender_id}@的消息：", decrypted_payload)

#         # 3. 获取本机设备信息，用于加密存储
#        device_info = auth.get_device_info()
        # device_info = auth.get_device_info()
        # cpu_id = device_info.get("cpu_id", "")
        # disk_id = device_info.get("disk_id", "")
        # product_id = device_info.get("product_id", "")

#          #调用存储加密函数：
#         encrypted_storage_message=did_interface. encrypt(cpu_id, disk_id, product_id, message)
#         #存储加密后的信息
#         save_group_message(group_id,sender_id,encrypted_storage_message,my_did)

        #通知前端，向前端发起请求，显示这条解密后的消息，并且做@提醒的特殊显示
        # request_display_notice(decrypted_payload)

